package com.lanou.bbs.controller;

import com.lanou.bbs.entity.User;
import com.lanou.bbs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @author 姚云鹏
 * Create at: 2018/6/8 9:24
 */
@Controller
@RequestMapping("/user")
public class UserController {
//    @Autowired
    @Resource
    private UserService userService;

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/toRegister")
    public String toRegister() {
        return "register";
    }

    @RequestMapping("/login")
    public String login(User user, HttpSession session, Model model) {
        // 1.接收请求参数
        System.out.println("***" + user.getUsername());

        // 2.调用service获取登录结果
        User u = userService.login(user);

        // 3.判断登录结果
        if (u != null) { // 3.1 登录成功
            // 3.1.1 将登录成功的user存session中，以保证登录状态
            session.setAttribute("user", u);

            // 3.1.2 跳转到主页/index.jsp
            return "redirect:/index.jsp";

        } else { // 3.2 登录失败
            // 3.2.1 model中存失败信息
            model.addAttribute("msg", "用户名或密码错误");
            model.addAttribute("user", user);

            // 3.2.2 跳转到登录页面
            return "login";
        }
    }

    @RequestMapping("/register")
    public String register(User user,Model model) {
        boolean rs = userService.register(user);

        if (rs) {
            return "redirect:toLogin";
        } else {
            model.addAttribute("msg", "注册失败");

            return "register";
        }
    }
}
